package com.longrise.android.byjk.plugins.course.coursedetail.healthrisk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BlurMaskFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.course.coursedetail.courseevaluate.ScoreActivity;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.bean.RiskCourseBean;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.catalogue.CatalogueChildItemVideo;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.catalogue.HealthRiskCatalogueFragment;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.intro.HealthRiskIntroFragment;
import com.longrise.android.byjk.plugins.course.coursedetail.learningagreement.LearningAgreementActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.assist.CourseHelper;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.assist.Flag;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.publicpage.NetworkAdviseActivity;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * Created by callxkj on 2018/1/14.
 * 健康风险管理师
 */

public class HealthRiskActivity extends BaseActivity2 implements View.OnClickListener {

    private ViewPager mVp;
    private TabLayout mTb;
    private Toolbar mToolbar;
    private AppBarLayout mAppbarlayout;
    private AppbarlayoutState mAppbarstate = AppbarlayoutState.STATE1;
    private int mRealPicHeight;
    private RelativeLayout mRltop;
    private CollapsingToolbarLayout mCoolapsing;
    private ImageView mIvtop;
    private String mCourseid;
    private boolean mIsEvaluate;
    private ImageView mIvtopright;
    private Button mBttop;
    private TextView mTvtop;
    private View mNetErrorView;
    private View mDefaultView;
    private VideoParams mLatestVideoParams;  //最近播放的视频参数
    private RelativeLayout mRltopright;
    private RelativeLayout mRl_refresh;
    private TextView mTv_netError_advise;
    private HealthRiskIntroFragment mHealthRiskIntroFragment;
    private HealthRiskCatalogueFragment mHealthRiskCatalogueFragment;


    public static void toPushActivity(Activity activity, String courseid) {
        Intent intent = new Intent(activity, HealthRiskActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("courseid", courseid);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mCourseid = bundle.getString("courseid");
        }
    }

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_healthrisk;
    }

    @Override
    public void setStatusBarColor() {
        super.setStatusBarColor();

    }

    @Override
    public void initView() {
        setToolbarVisible(false); //隐藏统一的toolbar

        mCoolapsing = (CollapsingToolbarLayout) findViewById(R.id.healthrisk_collapsing);
        mRltop = (RelativeLayout) findViewById(R.id.healthrisk_top_iv_root_rl);
        mAppbarlayout = (AppBarLayout) findViewById(R.id.healthrisk_appbarlayout);
        mToolbar = (Toolbar) findViewById(R.id.healthrisk_byjk_toolbar);
        mTb = (TabLayout) findViewById(R.id.healthrisk_tablayout);
        mVp = (ViewPager) findViewById(R.id.healthrisk_vp);
        mIvtop = (ImageView) findViewById(R.id.iv_topview);
        mIvtopright = (ImageView) findViewById(R.id.healthrisk_toolbar_right_iv);
        mBttop = (Button) findViewById(R.id.by_healthrisk_top_bt);
        mTvtop = (TextView) findViewById(R.id.by_healthrisk_top_tv);
        mRltopright = (RelativeLayout) findViewById(R.id.healthrisk_toolbar_right_rl);

        mNetErrorView = findViewById(R.id.coursedetail_neterror);
        mDefaultView = findViewById(R.id.coursedetail_default);
        mRl_refresh = (RelativeLayout) findViewById(R.id.by_neterror_coursedetail2_rl);
        mTv_netError_advise = (TextView) findViewById(R.id.by_neterror_coursedetail2_tv2);

        reSizeTopImage();
        getIntentData();
        initEvent();
        initVp();
    }

    @Override
    public void onToolbarBackClick() {

    }

    /**
     * 通过屏幕来 计算上面图片的高度
     */
    private void reSizeTopImage() {
        mRealPicHeight = AppUtil.getRealHeight(208);

        ViewGroup.LayoutParams layoutParams = mRltop.getLayoutParams();
        layoutParams.height = mRealPicHeight;
        mRltop.setLayoutParams(layoutParams);

        ViewGroup.LayoutParams layoutParams1 = mCoolapsing.getLayoutParams();
        layoutParams1.height = mRealPicHeight;
        mCoolapsing.setLayoutParams(layoutParams1);

    }

    public void initEvent() {
        mBttop.setOnClickListener(this);
        mRltopright.setOnClickListener(this);
        mRl_refresh.setOnClickListener(this);
        mTv_netError_advise.setOnClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mAppbarlayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                PrintLog.d(TAG, "hh:" + verticalOffset);
                if (verticalOffset >= -(0.5 * mRealPicHeight)) {
                    if (mAppbarstate == AppbarlayoutState.STATE2) {//如果以前是折叠状态 就转换状态
                        mToolbar.setTitle("");
                        mToolbar.setNavigationIcon(R.drawable.by_icon_general_ic_back_mask);
                        mAppbarstate = AppbarlayoutState.STATE1;
                        showEvalateIcon();
                    }
                } else {
                    if (mAppbarstate == AppbarlayoutState.STATE1) { //如果以前是展开状态 就转换为折叠状态
                        mToolbar.setTitle("健康风险管理师");
                        mToolbar.setNavigationIcon(R.drawable.ic_back_main);
                        mAppbarstate = AppbarlayoutState.STATE2;
                        showEvalateIcon();
                    }
                }
            }
        });
    }


    private void initVp() {
        mHealthRiskIntroFragment = HealthRiskIntroFragment.getInstance(mCourseid);
        mHealthRiskCatalogueFragment = HealthRiskCatalogueFragment.getInstance(mCourseid);
        HealthRiskPagerAdapter mAdapter = new HealthRiskPagerAdapter(getSupportFragmentManager(), mHealthRiskIntroFragment,
                mHealthRiskCatalogueFragment);
        mVp.setAdapter(mAdapter);
        mTb.setupWithViewPager(mVp);
        mVp.setCurrentItem(1, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.by_healthrisk_top_bt:
                checkNetWorkAndtoStudy(mLatestVideoParams);
                break;
            case R.id.healthrisk_toolbar_right_rl: //课程评价
                ScoreActivity.toPushActivity(this, mCourseid);
                break;
            case R.id.by_neterror_coursedetail2_rl: //刷新重试
                showLoadingDialog();
                mHealthRiskIntroFragment.refresh();
                mHealthRiskCatalogueFragment.refresh();
                break;
            case R.id.by_neterror_coursedetail2_tv2: //查看解决协议
                startActivity(NetworkAdviseActivity.class);
            default:
                break;
        }
    }


    private enum AppbarlayoutState {
        STATE1, //展开状态,这个状态toolbar不显示title
        STATE2  //折叠状态,这个状态toolbar显示title
    }

    /**
     * 设置顶部的image
     *
     * @param url iamgeurl
     */
    public void setImage(String url) {
        Glide.with(this)
                .load(url)
                .error(AppUtil.getResources().getDrawable(R.drawable.img03))
                .bitmapTransform(new BlurTransformation(mContext, 25, 4)) //“25”：设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”。
                .into(mIvtop);
    }

    /**
     * @param isEvaluate 课程是否已经被评价过
     */
    public void setCourseHasEvaluate(boolean isEvaluate) {
        this.mIsEvaluate = isEvaluate;
        showEvalateIcon();
    }

    /**
     * 显示网络错误页面
     */
    public void showNetErrorPage() {
        dismissLoadingDialog();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(AppUtil.getColor(R.color.colorPrimaryDark));
        }
        mDefaultView.setVisibility(View.GONE);
        mNetErrorView.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏默认页面 显示正常页面
     */
    public void dismissDefaultView() {
        dismissLoadingDialog();
        AppUtil.setTransparentStatusBar(this);
        mDefaultView.setVisibility(View.GONE);
        mNetErrorView.setVisibility(View.GONE);
    }

    /**
     * 切换toolbar右边的评价图片
     */
    private void showEvalateIcon() {
        if (mAppbarstate == AppbarlayoutState.STATE1) { //展开状态
            if (mIsEvaluate) {  //已经评价过
                mIvtopright.setBackgroundResource(R.drawable.by_icon_general_ic_graded_mask);
            } else {
                mIvtopright.setBackgroundResource(R.drawable.by_icon_general_ic_grade_mask);
            }

        } else if (mAppbarstate == AppbarlayoutState.STATE2) {  //折叠状态
            if (mIsEvaluate) {
                mIvtopright.setBackgroundResource(R.drawable.by_icon_general_ic_graded_mask_second);
            } else {
                mIvtopright.setBackgroundResource(R.drawable.by_icon_general_ic_grade_second);
            }
        }
    }

    /**
     * 设置顶部课程数据
     */
    public void setTopCourseData(EntityBean latelystudy, EntityBean[] catelogs, String studentno) {
        //是否已经学习过
        boolean hasstudy = latelystudy.getBoolean("hasstudy");
        Gson gson = new Gson();
        if (hasstudy) { //已经学习过
            mBttop.setText("继续学习");
            String lateplan = latelystudy.getString("lateplan");
            try {
                RiskCourseBean riskCourseBean = gson.fromJson(lateplan, RiskCourseBean.class);
                String cwid = riskCourseBean.getCurnode().getCwid();
                String dispname = riskCourseBean.getCurnode().getDispname();
                String pathno = riskCourseBean.getCurnode().getPathno();
                mTvtop.setText("最近学到：" + dispname);

                mLatestVideoParams = new VideoParams();
                mLatestVideoParams.mCourseId = mCourseid;
                mLatestVideoParams.mStudentNo = studentno;
                mLatestVideoParams.mCwid = cwid;
                mLatestVideoParams.mPathNo = pathno;
                mLatestVideoParams.mCwidName = dispname;

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {  //没有学习过
            mBttop.setText("开始学习");
            mTvtop.setText("您还未开始学习");

            //如果没有播放过这个课件 那么从第一个开始播放
            if (catelogs != null) {
                EntityBean catelog = catelogs[0];
                EntityBean[] nextmulus = catelog.getBeans("nextmulu");
                if (nextmulus != null) {
                    for (int y = 0; y < nextmulus.length; y++) {
                        EntityBean nextmulu = nextmulus[y];
                        Integer iscw1 = nextmulu.getInt("iscw");
                        if (iscw1 == 1) {
                            String course = nextmulu.getString("course");
                            RiskCourseBean riskCourseBean = gson.fromJson(course, RiskCourseBean.class);
                            mLatestVideoParams = new VideoParams();
                            mLatestVideoParams.mCourseId = mCourseid;
                            mLatestVideoParams.mStudentNo = studentno;
                            mLatestVideoParams.mCwid = riskCourseBean.getCurnode().getCwid();
                            mLatestVideoParams.mPathNo = riskCourseBean.getCurnode().getPathno();
                            mLatestVideoParams.mCwidName = riskCourseBean.getCurnode().getDispname();
                            break;
                        }
                    }
                }
            }
        }
    }


    /**
     * 检查是否是wifi网络
     */
    public void checkNetWorkAndtoStudy(final VideoParams videoParams) {
        if (netWorkComformWIFI()) {
            toStudy(1, videoParams);
        } else {
            //移动网络环境下：弹窗提示 是否允许进入课程播放页
            CourseHelper.showNetWorkStateDialog(mContext, Flag.TRANSFER_COURSE_DETAIL, new Flag.OnNextListener() {
                @Override
                public void onBack(boolean isCloseCurrentPage) {
                    //不做任何处理
                }

                @Override
                public void toNext() {
                    toStudy(2, videoParams);
                }
            });
        }
    }


    /**
     * 判断网络状态是否是WIFI（
     * 如果是移动网络环境下，判断用户是否已开启允许移动网络环境下学习视频
     * 否则只要不是移动网络环境下（包括没有网络）直接进入播放器
     */
    private boolean netWorkComformWIFI() {
        //判断当前是否是移动网络环境
        boolean netWorkState = NetUtil.isDataNet();
        if (netWorkState) {
            //当前为移动网络环境，判断是否允许了移动网络环境下播放器视频课件,如果允许则返回true;
            String allow = Control.getCellularNetWork();
            return "1".equals(allow) ? true : false;
        }
        //否则直接返回true
        return true;
    }


    /**
     * 立即学习
     */
    private void toStudy(int flag, VideoParams videoParams) {
        if (flag == 2) {  //如果是移动网络 用户点击了允许 就添加标记
            videoParams.mDataNet = true;
        }
        LearningAgreementActivity.toCheckAndShow((Activity) mContext, videoParams);
    }

}
